package com.fowo.api.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.map.MapUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.controller.purchase.excelPo.warehouseBinExcelPo;
import com.fowo.api.controller.purchase.excelPo.warehouseBinProductExcelPo;
import com.fowo.api.controller.purchase.importPo.*;
import com.fowo.api.controller.purchase.vo.*;
import com.fowo.api.entity.*;
import com.fowo.api.inventory.entity.Inventory;
import com.fowo.api.inventory.entity.InventoryPlacement;
import com.fowo.api.inventory.model.InventoryStorageVo;
import com.fowo.api.inventory.model.SimpleInventoryItem;
import com.fowo.api.inventory.model.TargetTypeEnum;
import com.fowo.api.inventory.model.form.InventoryStorageFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.inventory.service.InventoryService;
import com.fowo.api.inventory.service.impl.InventoryPlacementServiceImpl;
import com.fowo.api.inventory.service.impl.InventoryServiceImpl;
import com.fowo.api.mapper.WarehouseBinDMapper;
import com.fowo.api.mapper.WarehouseBinMapper;
import com.fowo.api.model.attribute.AttributeExcelPo;
import com.fowo.api.model.stock.in.product.StockInProductItemVo;
import com.fowo.api.model.warehouse.bin.WarehouseBinItemVo;
import com.fowo.api.model.warehouse.bin.WarehouseBinSearchParamPo;
import com.fowo.api.model.warehouse.bin.WarehouseBinVo;
import com.fowo.api.model.warehouse.bin.constant.WarehouseBinStatusEnums;
import com.fowo.api.model.warehouse.bin.products.WarehouseBinProductsItemVo;
import com.fowo.api.model.warehouse.bin.products.WarehouseBinProductsSearchParamPo;
import com.fowo.api.model.warehouse.bin.products.WarehouseBinProductsVo;
import com.fowo.api.service.*;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
@DS("ds24")
public class WarehouseBinDServiceImpl {
    @Resource
    private WarehouseBinServiceImpl warehouseBinService;
    @Resource
    protected WarehouseBinProductsServiceImpl warehouseBinProductsService;
    @Resource
    private WarehouseServiceImpl warehouseService;
    @Resource
    protected SysImportTemplateService importTemplateService;
    @Resource
    protected FileService fileService;
    @Resource
    protected Validator validator;
    @Resource
    private ProductServiceImpl productService;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private WarehouseBinDMapper warehouseBinDMapper;
    @Resource
    private InventoryPlacementServiceImpl inventoryPlacementService;

    @Resource
    private SysDictService sysDictService;
    @Resource
    private ListingFatherServiceImpl listingFatherService;
    @Resource
    private InventoryBusinessService inventoryBusinessService;
    @Resource
    private InventoryServiceImpl inventoryService;
    @Resource
    private WarehouseBinMapper warehouseBinMapper;

    public List<ImportRow<WarehouseBinImportPo>> importPreview(
            SysFile sysFile,
            Long templateId,
            boolean allowOverrides,
            Long wid
    ) throws Exception {
        SysImportTemplate importTemplate = null;
        if (templateId != null && templateId > 0) {
            importTemplate = importTemplateService.getById(templateId);
            if (importTemplate == null) {
                throw new RException("指定的模版不可用！");
            }
        }
        Warehouse byId = warehouseService.getById(wid);
    Assert.notNull(byId,"仓库不存在!");
        Map<String, Object> variables = new HashMap<>();
        try (InputStream in = fileService.read(sysFile)) {
            List<ImportRow<WarehouseBinImportPo>> rows = new ArrayList<>();

            // 读取 Excel 到 rows
            EasyExcel
                    .read(in)
                    .useDefaultListener(false)
                    .registerReadListener(
                            new TemplateModelBuildEventListener<>(
                                    WarehouseBinImportPo.class,
                                    importTemplate
                            ) {
                                @Override
                                public void invokeRow(
                                        WarehouseBinImportPo row,
                                        AnalysisContext cxt
                                ) {
                                    WarehouseBinVo vo = new WarehouseBinVo();
                                    ImportRow<WarehouseBinImportPo> ir = excelToImportRow(
                                            row,
                                            cxt.readRowHolder().getRowIndex(),
                                            vo,
                                            variables,
                                            allowOverrides
                                    );
                                    if (ir.isEmptyRow()) {
                                        return;
                                    }
                                    if (allowOverrides) {
                                        // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
                                    }
                                    rows.add(ir);
                                }
                            }
                    )
                    .sheet()
                    .doRead();
            return rows;
        }
    }

    /**
     * 导入单行处理
     * @param row 要导入的行
     * @param rowNumber 所在行号
     * @param vo 输出VO,可空
     * @param variables 变量池，用于在一次导入过程中保存临时信息
     * @param allowOverrides 允许覆盖
     * @return 导入行对象
     */
    protected ImportRow<WarehouseBinImportPo> excelToImportRow(
            WarehouseBinImportPo row,
            Integer rowNumber,
            WarehouseBinVo vo,
            Map<String, Object> variables,
            boolean allowOverrides
    ) {
        ImportRow<WarehouseBinImportPo> ir = new ImportRow<WarehouseBinImportPo>();
        ir.setRowNumber(rowNumber);
        ir.setRow(row);
        if (SheetUtils.isAllFieldsEmpty(row)) {
            ir.setEmptyRow(true);
            ir.addError("", "空行");
            return ir;
        }
        final Set<ConstraintViolation<WarehouseBinImportPo>> validate = validator.validate(
                row
        );
        boolean isOutputVo = vo != null;
        if (!isOutputVo) {
            vo = new WarehouseBinVo();
        }
        BeanUtils.copyProperties(row, vo);
        // 收集基本校验错误
        ir.initErrors(validate, WarehouseBinImportPo.class);

        // 一般数据处理
        if (StringUtils.hasText(row.getStatus())) {
            vo.setStatus(WarehouseBinStatusEnums.toValue(row.getStatus()));
            if (vo.getStatus() == null) {
                ir.addError("status", "仓位状态只能是：“启用”, “关闭”");
            }
        }
        vo.setAvailableSku(SheetUtils.tryToInteger(row.getAvailableSku()));
        if (StringUtils.hasText(row.getType())) {
            List<SysDictAllItem> typeItems = (List<SysDictAllItem>) variables.computeIfAbsent(
                    "type",
                    n -> sysDictService.getDictItems("SCM00018")
            );
            WarehouseBinVo finalVo = vo;
            typeItems
                    .stream()
                    .filter(i -> i.getItemText().equals(row.getType()))
                    .findFirst()
                    .ifPresent(i -> finalVo.setType(i.getItemValue()));
        }
        return ir;
    }

    /**
     * 完成导入
     * @param rows 预导入的行信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void importDone(
            List<ImportRow<WarehouseBinImportPo>> rows,
            Long templateId,
            Long wid
    ) throws Exception {
        SysImportTemplate importTemplate = null;
        if (templateId != null && templateId > 0) {
            importTemplate = importTemplateService.getById(templateId);
            if (importTemplate == null) {
                throw new RException("指定的模版不可用！");
            }
        }
        Warehouse byId = warehouseService.getById(wid);
        Assert.notNull(byId,"仓库不存在!");
        List<Long> importedIdList = new ArrayList<>();
        Map<String, Object> variables = new HashMap<>();
        for (int i = 0; i < rows.size(); i++) {
            ImportRow<WarehouseBinImportPo> row = rows.get(i);
            Long updateId = row.getUpdateId();
            WarehouseBinVo vo = new WarehouseBinVo();
            row =
                    excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
            if (row.getErrors() != null && row.getErrors().size() > 0) {
                throw new RException(
                        String.format(
                                "第%d行（Excel第%d行）数据验证错误：%s",
                                i + 1,
                                row.getRowNumber(),
                                row.getJoinErrorMessage()
                        )
                );
            }
            if (updateId != null) {
                vo.setId(updateId);
            }
            if (updateId == null) {
                WarehouseBin one = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                        .eq(WarehouseBin::getWarehouseId,wid)
                        .eq(WarehouseBin::getStorageBin, vo.getStorageBin()));
                vo.setWarehouseId(wid);
                Assert.isNull(one,one!=null?one.getStorageBin()+"已存在":null);
                importedIdList.add(warehouseBinService.create(vo));
            }
        }
    }


    public List<ImportRow<WarehouseBinProductImportPo>> importPreview2(
            SysFile sysFile,
            Long templateId,
            boolean allowOverrides,
            Long wid
    ) throws Exception {
        SysImportTemplate importTemplate = null;
        if (templateId != null && templateId > 0) {
            importTemplate = importTemplateService.getById(templateId);
            if (importTemplate == null) {
                throw new RException("指定的模版不可用！");
            }
        }
        Map<String, Object> variables = new HashMap<>();
        try (InputStream in = fileService.read(sysFile)) {
            List<ImportRow<WarehouseBinProductImportPo>> rows = new ArrayList<>();

            // 读取 Excel 到 rows
            EasyExcel
                    .read(in)
                    .useDefaultListener(false)
                    .registerReadListener(
                            new TemplateModelBuildEventListener<>(
                                    WarehouseBinProductImportPo.class,
                                    importTemplate
                            ) {
                                @Override
                                public void invokeRow(
                                        WarehouseBinProductImportPo row,
                                        AnalysisContext cxt
                                ) {
                                    WarehouseBinProductImportPo vo = new WarehouseBinProductImportPo();
                                    ImportRow<WarehouseBinProductImportPo> ir = excelToImportRow2(
                                            row,
                                            cxt.readRowHolder().getRowIndex(),
                                            vo,
                                            variables,
                                            allowOverrides,
                                            wid
                                    );
                                    if (ir.isEmptyRow()) {
                                        return;
                                    }
                                    if (allowOverrides) {
                                        // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
                                    }
                                    rows.add(ir);
                                }
                            }
                    )
                    .sheet()
                    .doRead();
            return rows;
        }
    }
    protected ImportRow<WarehouseBinProductImportPo> excelToImportRow2(
            WarehouseBinProductImportPo row,
            Integer rowNumber,
            WarehouseBinProductImportPo vo,
            Map<String, Object> variables,
            boolean allowOverrides,
            Long wid
    ) {
        ImportRow<WarehouseBinProductImportPo> ir = new ImportRow<WarehouseBinProductImportPo>();
        ir.setRowNumber(rowNumber);
        ir.setRow(row);
        if (SheetUtils.isAllFieldsEmpty(row)) {
            ir.setEmptyRow(true);
            ir.addError("", "空行");
            return ir;
        }
        final Set<ConstraintViolation<WarehouseBinProductImportPo>> validate = validator.validate(
                row
        );
        boolean isOutputVo = vo != null;
        if (!isOutputVo) {
            vo = new WarehouseBinProductImportPo();
        }
        BeanUtils.copyProperties(row, vo);
        // 收集基本校验错误
        ir.initErrors(validate, WarehouseBinProductImportPo.class);
        WarehouseBin warehouseBin = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                .eq(WarehouseBin::getWarehouseId,wid)
                .eq(WarehouseBin::getStorageBin, row.getStorageBin()));
        if (StringUtils.hasText(row.getStorageBin())) {
            if(warehouseBin==null){
                ir.addError("storageBin", row.getStorageBin()+"仓位不存在");
            }
        }
        Product product = productService.getOne(Wrappers.<Product>query().lambda().eq(Product::getSku, row.getSku()));
        if (StringUtils.hasText(row.getSku())) {
            if(product==null){
                ir.addError("SKU", row.getSku()+"产品不存在");
            }
        }
        ShopInfo shopInfo =null;
        if (StringUtils.hasText(row.getShop())) {
            shopInfo=shopInfoService.getOne(Wrappers.<ShopInfo>query().lambda().eq(ShopInfo::getShopName, row.getShop()));
            if(shopInfo==null){
                ir.addError("shopName", row.getShop()+"店铺不存在");
            }
        }
        ListingFather listingFather =null;

        if (StringUtils.hasText(row.getFnsku())&&shopInfo!=null) {
            listingFather = listingFatherService.getOne(Wrappers.<ListingFather>query().lambda()
                    .eq(ListingFather::getFnsku, row.getFnsku())
                    .eq(ListingFather::getShop, shopInfo.getId())
                    .eq(ListingFather::getSku, row.getSku()));
            if(listingFather==null){
                ir.addError("FNSKU", row.getFnsku()+",fnsku不存在");
            }
            if(shopInfo==null){
                ir.addError("shop", row.getShop()+",店铺不存在");
            }
        }
        Boolean isTrue=true;
        if(row.getStatus()!=null){
            if(row.getStatus().equals("是")){
                isTrue=false;
            }
        }
//        if(product!=null&&warehouseBin!=null&&isTrue){
//            //判断店铺是否绑定了
//            panduanshifoubangding(row, ir, warehouseBin, product, shopInfo, listingFather);
//            panduancangku(row, ir, warehouseBin, product);
//        }
        return ir;
    }

    private void panduanshifoubangding(WarehouseBinProductImportPo row, ImportRow<WarehouseBinProductImportPo> ir, WarehouseBin warehouseBin, Product product, ShopInfo shopInfo, ListingFather listingFather) {
        QueryWrapper<WarehouseBinProducts> queryWrapper=new QueryWrapper();
        queryWrapper.eq("parent_id",warehouseBin!=null?warehouseBin.getId():null);
        queryWrapper.eq("product_id",product!=null?product.getId():null);
        if(StringUtils.hasText(row.getShop())&&shopInfo!=null){
            queryWrapper.eq("shop_id",shopInfo.getId());
        }else{
            queryWrapper.isNull("shop_id");
        }
        if(StringUtils.hasText(row.getFnsku())&&listingFather!=null){
            queryWrapper.eq("fnsku_name",listingFather.getFnsku());
        }else{
            queryWrapper.isNull("fnsku_name");
        }
        WarehouseBinProducts one = warehouseBinProductsService.getOne(queryWrapper);
        if(one!=null){
            ir.addError("sku", row.getSku()+"已绑定"+row.getStorageBin());
        }
    }

    private void panduancangku(WarehouseBinProductImportPo row, ImportRow<WarehouseBinProductImportPo> ir, WarehouseBin warehouseBin, Product product) {
        //判断是否绑定同一个仓库
        WarehouseBinParam search=new WarehouseBinParam();
        search.setProductId(product.getId());
        search.setWarehouseId(warehouseBin.getWarehouseId());
        List<com.fowo.api.controller.purchase.vo.warehouseBin> wareBin = warehouseBinDMapper.getWareBin(search);
        if(wareBin.size()>0){
            //判断是不是一个仓位
            warehouseBin warehouseBin2 = wareBin.get(0);
            if(warehouseBin2.getId().longValue()!=warehouseBin.getId().longValue()){
                ir.addError("sku", row.getSku()+"产品已经绑定了仓位"+warehouseBin2.getName());
            }
        }
    }
@Transactional(rollbackFor = Exception.class)
    public void importDone2(List<ImportRow<WarehouseBinProductImportPo>> rows, Long templateId,Long wid) throws Exception {

        SysImportTemplate importTemplate = null;
        if (templateId != null && templateId > 0) {
            importTemplate = importTemplateService.getById(templateId);
            if (importTemplate == null) {
                throw new RException("指定的模版不可用！");
            }
        }
        for (int i = 0; i < rows.size(); i++) {
            ImportRow<WarehouseBinProductImportPo> row = rows.get(i);
            WarehouseBinProductImportPo warehouseBinProductImportPo=row.getRow();
            WarehouseBin one = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                    .eq(WarehouseBin::getStorageBin, warehouseBinProductImportPo.getStorageBin())
                    .eq(WarehouseBin::getWarehouseId,wid));
            Assert.notNull(one,warehouseBinProductImportPo.getStorageBin()+"不存在!");

            Product one1 = productService.getOne(Wrappers.<Product>query().lambda().eq(Product::getSku, warehouseBinProductImportPo.getSku()));
            Assert.notNull(one1,warehouseBinProductImportPo.getSku()+"不存在!");
            ShopInfo one2 =null;
            if(warehouseBinProductImportPo.getShop()!=null){
                 one2 = shopInfoService.getOne(Wrappers.<ShopInfo>query().lambda().eq(ShopInfo::getShopName, warehouseBinProductImportPo.getShop()));
                Assert.notNull(one2,warehouseBinProductImportPo.getShop()+"不存在!");
            }
            ListingFather one3=null;
            if(warehouseBinProductImportPo.getShop()!=null&&warehouseBinProductImportPo.getFnsku()!=null){
                one3 = listingFatherService.getOne(Wrappers.<ListingFather>query().lambda()
                        .eq(ListingFather::getFnsku, warehouseBinProductImportPo.getFnsku())
                        .eq(ListingFather::getShop, one2.getId())
                        .eq(ListingFather::getSku, one1.getSku()));
                Assert.notNull(one3,warehouseBinProductImportPo.getFnsku()+"fnsku不存在！");
            }
            QueryWrapper<WarehouseBinProducts> queryWrapper=new QueryWrapper();
            queryWrapper.eq("parent_id",one.getId());
            queryWrapper.eq("product_id",one1.getId());
            if(warehouseBinProductImportPo.getShop()!=null){
                queryWrapper.eq("shop_id",one2.getId());
            }else{
                queryWrapper.isNull("shop_id");
            }
            if(warehouseBinProductImportPo.getShop()!=null&&warehouseBinProductImportPo.getFnsku()!=null){
                queryWrapper.eq("fnsku_name",one3.getFnsku());
            }else{
                queryWrapper.isNull("fnsku_name");
            }
            WarehouseBinProducts one4 = warehouseBinProductsService.getOne(queryWrapper);
            if(warehouseBinProductImportPo.getStatus()!=null&&warehouseBinProductImportPo.getStatus().equals("是")){
                //解除关联直接删掉
                Assert.notNull(one4,one4.getProductId()+"没有绑定库位");
                warehouseBinProductsService.delete(one4.getId());
            }else{
                if(one4==null){
                    //判断同一个仓库一个产品只能绑定一个仓位
                    //查询在这个仓库下面是否已经绑定过了
//                    WarehouseBinParam search=new WarehouseBinParam();
//                    search.setProductId(one1.getId());
//                    search.setWarehouseId(one.getWarehouseId());
//                    List<warehouseBin> wareBin = warehouseBinDMapper.getWareBin(search);
//                    if(wareBin.size()!=0){
//                        Assert.isTrue(false,wareBin.get(0).getName()+"已绑定这个仓位");
//                    }
                    WarehouseBinProductsVo model=new WarehouseBinProductsVo();
                    model.setParentId(one.getId());
                    model.setProductId(one1.getId());
                    model.setShopId(one2!=null?one2.getId():null);
                    model.setFnsku(one3!=null?one3.getId():null);
                    model.setFnskuName(one3!=null?one3.getFnsku():null);
                    model.setMsku(one3!=null?one3.getMsku():null);
                    model.setSku(one1.getSku());
                    model.setProductName(one1.getName());
                    model.setAsin(one3!=null?one3.getAsin():null);
                    warehouseBinProductsService.create(model);
                }
            }
        }

    }


    public void export(
            Long templateId,
            WarehouseBinProductsSearchParamPo search,
            HttpServletResponse response
    ) throws Exception {
        search.setPageSize(10000);
        int current = 1;
        List<WarehouseBinProductsExcelPo> items = new ArrayList<WarehouseBinProductsExcelPo>();
        while (true) {
            search.setCurrent(current);
            Page<WarehouseBinProductsItemVo> page = warehouseBinProductsService.pageSearch(search);
            if (page.getTotal() > 10000) {
                throw new RException("导出记录数超出限制！");
            }
            List<WarehouseBinProductsItemVo> list = page.getRecords();
            if (list.isEmpty()) {
                break;
            }
            for (WarehouseBinProductsItemVo item : list) {
                WarehouseBinProductsExcelPo excel = new WarehouseBinProductsExcelPo();
                BeanUtils.copyProperties(item, excel);
                ListingFather byId = listingFatherService.getById(item.getFnsku());
                excel.setFnsku(byId!=null?byId.getFnsku():null);

                ShopInfo byId1 = shopInfoService.getById(item.getShopId());
                excel.setShopName(byId1!=null?byId1.getShopName():null);
                Product byId2 = productService.getById(item.getProductId());
                excel.setSku(byId2!=null?byId2.getSku():null);
                items.add(excel);
            }
            if (list.size() < 10000) {
                break;
            }
            current++;
        }

        String fileName = String.format(
                "仓位子表(%s).xlsx",
                DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
        );
        ResponseUtils.setAttachmentFileName(response, fileName);
        EasyExcel
                .write(response.getOutputStream())
                .registerWriteHandler(new CustomExcelHandler())
                .sheet()
                .head(WarehouseBinProductsExcelPo.class)
                .doWrite(items);
    }

    public List<ImportRow<wareHouseInventoryImportPo>> importInitializationInventory(SysFile sysFile, Long templateId, boolean allowOverrides) throws IOException {

        SysImportTemplate importTemplate = null;
        if (templateId != null && templateId > 0) {
            importTemplate = importTemplateService.getById(templateId);
            if (importTemplate == null) {
                throw new RException("指定的模版不可用！");
            }
        }
        Map<String, Object> variables = new HashMap<>();
        try (InputStream in = fileService.read(sysFile)) {
            List<ImportRow<wareHouseInventoryImportPo>> rows = new ArrayList<>();

            // 读取 Excel 到 rows
            EasyExcel
                    .read(in)
                    .useDefaultListener(false)
                    .registerReadListener(
                            new TemplateModelBuildEventListener<>(
                                    wareHouseInventoryImportPo.class,
                                    importTemplate
                            ) {
                                @Override
                                public void invokeRow(
                                        wareHouseInventoryImportPo row,
                                        AnalysisContext cxt
                                ) {
                                    WarehouseBinVo vo = new WarehouseBinVo();
                                    ImportRow<wareHouseInventoryImportPo> ir = excelToImportRow3(
                                            row,
                                            cxt.readRowHolder().getRowIndex(),
                                            vo,
                                            variables,
                                            allowOverrides
                                    );
                                    if (ir.isEmptyRow()) {
                                        return;
                                    }
                                    if (allowOverrides) {
                                        // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
                                    }
                                    rows.add(ir);
                                }
                            }
                    )
                    .sheet()
                    .doRead();
            return rows;
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void importDone3(List<ImportRow<wareHouseInventoryImportPo>> rows) throws Exception {
        for(int i=0;i<rows.size();i++){
            ImportRow<wareHouseInventoryImportPo> wareHouseInventoryImportPoImportRow = rows.get(i);
            wareHouseInventoryImportPo row= wareHouseInventoryImportPoImportRow.getRow();
            Warehouse warehouse = warehouseService.getOne(Wrappers.<Warehouse>query().lambda().eq(Warehouse::getName, row.getWName()));
            Product product = productService.getOne(Wrappers.<Product>query().lambda().eq(Product::getSku, row.getSKU()));
            ShopInfo shopInfo = shopInfoService.getOne(Wrappers.<ShopInfo>query().lambda().eq(ShopInfo::getShopName, row.getShopName()));
            ListingFather fnsku=null;
            WarehouseBin availableBin=null;
            WarehouseBin rejectBin=null;
            if(row.getAvailableBin()!=null){
                availableBin = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                        .eq(WarehouseBin::getStorageBin, row.getAvailableBin())
                        .eq(WarehouseBin::getWarehouseId,warehouse.getId()));
            }else{
                availableBin = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                        .eq(WarehouseBin::getStorageBin, "可用暂存")
                        .eq(WarehouseBin::getWarehouseId,warehouse.getId()));
            }
            if(row.getRejectBin()!=null){
                rejectBin = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                        .eq(WarehouseBin::getStorageBin, row.getAvailableBin())
                        .eq(WarehouseBin::getWarehouseId,warehouse.getId()));
            }else{
                rejectBin = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                        .eq(WarehouseBin::getStorageBin, "次品暂存")
                        .eq(WarehouseBin::getWarehouseId,warehouse.getId()));
            }
            if (StringUtils.hasText(row.getFNSKU())) {
                fnsku = listingFatherService.getOne(Wrappers.<ListingFather>query().lambda()
                        .eq(ListingFather::getFnsku, row.getFNSKU())
                        .eq(ListingFather::getShop, row.getShopName())
                        .eq(ListingFather::getSku, row.getSKU()));
            }
            //查询是否有库存
            QueryWrapper<Inventory> queryWrapper=new QueryWrapper();
            queryWrapper.eq("item_id",product.getId());
            queryWrapper.eq("stock_id",warehouse.getId());
            if(shopInfo!=null){
                queryWrapper.eq("shop_id",shopInfo.getId());
            }else{
                queryWrapper.isNull("shop_id");
            }
            if(fnsku!=null){
                queryWrapper.eq("fn_sku",fnsku.getId());
            }else{
                queryWrapper.isNull("fn_sku");
            }
            Inventory one = inventoryService.getOne(queryWrapper);
            if(one==null){
                if(row.getAvailableStock()!=null&&new BigDecimal(row.getAvailableStock()).intValue()>0){
                    InventoryStorageFormVo formVo = prepareRuku(wareHouseInventoryImportPoImportRow.getRow(),warehouse,product,shopInfo,fnsku,availableBin,rejectBin,0);
                    inventoryBusinessService.storage(formVo);
                }
                if(row.getRejectStock()!=null&&new BigDecimal(row.getRejectStock()).intValue()>0){
                    InventoryStorageFormVo formVo2 = prepareRuku(wareHouseInventoryImportPoImportRow.getRow(),warehouse,product,shopInfo,fnsku,availableBin,rejectBin,1);
                    inventoryBusinessService.storage(formVo2);
                }
            }


        }
    }

    private InventoryStorageFormVo prepareRuku(wareHouseInventoryImportPo row,
                                               Warehouse warehouse,
                                               Product product,
                                               ShopInfo shopInfo,
                                               ListingFather fnsku,
                                               WarehouseBin availableBin,
                                               WarehouseBin rejectBin,
                                               int type) {

            JwtUserInfo jwtUserInfo = JwtUserInfo.fromHeader();

            InventoryStorageFormVo formVo=new InventoryStorageFormVo();
            if(type==0){
                formVo.setTo(TargetTypeEnum.Normal);
            }else{
                formVo.setTo(TargetTypeEnum.Defect);
            }
            formVo.setFormNum(null);
            formVo.setFormOperator(jwtUserInfo.getUserId().toString());
            formVo.setStockId(warehouse.getId());
            SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
            inventoryItem.setId(product.getId());
            InventoryStorageVo storageItem = new InventoryStorageVo();
            storageItem.setItem(inventoryItem);
            if(type==0){
                storageItem.setQty( new BigDecimal(row.getAvailableStock()!=null?row.getAvailableStock():"0"));
            }else{
                storageItem.setQty( new BigDecimal(row.getRejectStock()!=null?row.getRejectStock():"0"));
            }

            storageItem.setShopId(
                    shopInfo==null
                            ? null
                            : String.valueOf(shopInfo.getId())
            );
            storageItem.setFnSku(
                    fnsku==null
                            ? null
                            : String.valueOf(fnsku.getId())
            );
            Map<Long, Integer> binIds = new HashMap<>();
            if(type==0){
                binIds.put(
                        availableBin.getId(),
                        Integer.parseInt(
                                String.valueOf(row.getAvailableStock()).equals("null")
                                        ? "0"
                                        : new BigDecimal(row.getAvailableStock()).setScale(0).toString()
                        )
                );
            }else{
                binIds.put(
                        rejectBin.getId(),
                        Integer.parseInt(
                                String.valueOf(row.getRejectStock()).equals("null")
                                        ? "0"
                                        : new BigDecimal(row.getRejectStock()).setScale(0).toString()
                        )
                );
            }
            storageItem.setBinIds(binIds);

            storageItem.setFromBinIdsType(TargetTypeEnum.Normal);

            formVo.add(storageItem);
        return formVo;
    }

    protected ImportRow<wareHouseInventoryImportPo> excelToImportRow3(
            wareHouseInventoryImportPo row,
            Integer rowNumber,
            WarehouseBinVo vo,
            Map<String, Object> variables,
            boolean allowOverrides
    ) {
        ImportRow<wareHouseInventoryImportPo> ir = new ImportRow<wareHouseInventoryImportPo>();
        ir.setRowNumber(rowNumber);
        ir.setRow(row);
        if (SheetUtils.isAllFieldsEmpty(row)) {
            ir.setEmptyRow(true);
            ir.addError("", "空行");
            return ir;
        }
        // 一般数据处理
//        if (StringUtils.hasText(row.getSKU())) {
//            vo.setStatus(WarehouseBinStatusEnums.toValue(row.getSKU()));
//
//            if (vo.getStatus() == null) {
//                ir.addError("status", "仓位状态只能是：“启用”, “关闭”");
//            }
//        }
        //warehouseService

        final Set<ConstraintViolation<wareHouseInventoryImportPo>> validate = validator.validate(
                row
        );
        boolean isOutputVo = vo != null;
        if (!isOutputVo) {
            vo = new WarehouseBinVo();
        }
        BeanUtils.copyProperties(row, vo);
        // 收集基本校验错误
        ir.initErrors(validate, wareHouseInventoryImportPo.class);
        if (StringUtils.hasText(row.getWName())) {

            Warehouse one = warehouseService.getOne(Wrappers.<Warehouse>query().lambda().eq(Warehouse::getName, row.getWName()));
            if(one==null){
                ir.addError("wName", row.getWName()+"仓库不存在");
            }
        }
        if (StringUtils.hasText(row.getSKU())) {
            Product one = productService.getOne(Wrappers.<Product>query().lambda().eq(Product::getSku, row.getSKU()));
            if(one==null){
                ir.addError("SKU", row.getSKU()+"产品不存在");
            }
        }
        if (StringUtils.hasText(row.getShopName())) {
            ShopInfo one = shopInfoService.getOne(Wrappers.<ShopInfo>query().lambda().eq(ShopInfo::getShopName, row.getShopName()));
            if(one==null){
                ir.addError("shopName", row.getShopName()+"店铺不存在");
            }
        }
        if (StringUtils.hasText(row.getFNSKU())) {
            ListingFather one = listingFatherService.getOne(Wrappers.<ListingFather>query().lambda()
                    .eq(ListingFather::getFnsku, row.getFNSKU())
                    .eq(ListingFather::getShop, row.getShopName())
                    .eq(ListingFather::getSku, row.getSKU()));
            if(one==null){
                ir.addError("FNSKU", row.getFNSKU()+"fnsku不存在");
            }
        }
        //availableBin
        if (StringUtils.hasText(row.getAvailableBin())) {
            Warehouse one = warehouseService.getOne(Wrappers.<Warehouse>query().lambda().eq(Warehouse::getName, row.getWName()));
            WarehouseBin one1 = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                    .eq(WarehouseBin::getStorageBin, row.getAvailableBin())
                    .eq(WarehouseBin::getWarehouseId,one.getWid()));
            if(one1==null){
                ir.addError("availableBin", row.getAvailableBin()+"可用仓位不存在");
                if(!one1.getType().equals("5")){
                    ir.addError("availableBin", row.getAvailableBin()+"不是可用仓位");
                }
            }
        }
        if (StringUtils.hasText(row.getRejectBin())) {
            Warehouse one = warehouseService.getOne(Wrappers.<Warehouse>query().lambda().eq(Warehouse::getName, row.getWName()));
            WarehouseBin one1 = warehouseBinService.getOne(Wrappers.<WarehouseBin>query().lambda()
                    .eq(WarehouseBin::getStorageBin, row.getRejectBin())
                    .eq(WarehouseBin::getWarehouseId,one.getWid()));
            if(one1==null){
                ir.addError("rejectBin", row.getAvailableBin()+"次品仓位不存在");
                if(!one1.getType().equals("6")){
                    ir.addError("rejectBin", row.getAvailableBin()+"不是次品仓位");
                }
            }
        }
        return ir;
    }

    public void exportCangWei(Long templateId, WarehouseBinParam search, HttpServletResponse response) throws IOException {
        Page page = search.toPage();
        page.setSize(10000);//1691268209998966785
//        search.setWarehouseId(Long.parseLong("1691268209998966785"));
        Page<WarehouseBinItemDVo> warehouseBinItemDVoPage = warehouseBinDMapper.pageSearch(page, search);
        List<WarehouseBinItemDVo> records = warehouseBinItemDVoPage.getRecords();
        List<warehouseBinExcelPo> items = new ArrayList<warehouseBinExcelPo>();
        for(int i=0;i<records.size();i++){
            warehouseBinExcelPo warehouseBinExcelPo=new warehouseBinExcelPo();
            WarehouseBinItemDVo warehouseBinItemDVo = records.get(i);
            Warehouse byId = warehouseService.getById(warehouseBinItemDVo.getWarehouseId());
            warehouseBinExcelPo.setWarehouseIdName(byId.getName());
            warehouseBinExcelPo.setUseType(warehouseBinItemDVo.getStatus().equals("1")?"启用":"关闭");
            warehouseBinExcelPo.setType(warehouseBinItemDVo.getType().equals("5")?"可用":"次品");
            warehouseBinExcelPo.setStorageBin(warehouseBinItemDVo.getStorageBin());
            items.add(warehouseBinExcelPo);
        }
        String fileName = String.format("仓位(%s).xlsx", DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME));
        ResponseUtils.setAttachmentFileName(response, fileName);
        EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(new CustomExcelHandler())
                .sheet()
                .head(warehouseBinExcelPo.class)
                .doWrite(items);
    }

    public void exportCangWeiGuanXi(Long templateId, WarehouseBinParam search, HttpServletResponse response) throws IOException{
        Page page = search.toPage();
        page.setSize(10000);//1691268209998966785
//        search.setWarehouseId(Long.parseLong("1691268209998966785"));
        Page<WarehouseBinItemDVo> warehouseBinItemDVoPage = warehouseBinDMapper.pageSearch(page, search);
        List<WarehouseBinItemDVo> records = warehouseBinItemDVoPage.getRecords();
        List<warehouseBinProductExcelPo> items = new ArrayList<warehouseBinProductExcelPo>();
        for(int i=0;i<records.size();i++){
            warehouseBinProductExcelPo warehouseBinExcelPo=new warehouseBinProductExcelPo();
            WarehouseBinItemDVo warehouseBinItemDVo = records.get(i);
            Warehouse byId = warehouseService.getById(warehouseBinItemDVo.getWarehouseId());
            warehouseBinExcelPo.setWarehouseIdName(byId!=null?byId.getName():null);
            warehouseBinExcelPo.setUseType(warehouseBinItemDVo.getStatus().equals("1")?"启用":"关闭");
            warehouseBinExcelPo.setType(warehouseBinItemDVo.getType().equals("5")?"可用":"次品");
            warehouseBinExcelPo.setStorageBin(warehouseBinItemDVo.getStorageBin());
            QueryWrapper<WarehouseBinProducts> queryWrapper2=new QueryWrapper<>();
            queryWrapper2.eq("parent_id",warehouseBinItemDVo.getId());
//            if(search.getShopId()!=null){
//                queryWrapper2.eq("shop_id",search.getShopId());
//            }
//            if(search.getFSku()!=null){
//                queryWrapper2.like("fnsku_name",search.getFSku());
//            }
//            if(search.getSku()!=null){
//                queryWrapper2.like("sku",search.getSku());
//            }
//            if(search.getName()!=null){
//                queryWrapper2.like("product_name",search.getName());
//            }
            List<WarehouseBinProducts> list = warehouseBinProductsService.list(queryWrapper2);
            if(list.size()>0){
                list.forEach(x->{
                    warehouseBinProductExcelPo warehouseBinExcelPo1=new warehouseBinProductExcelPo();
                    BeanUtils.copyProperties(warehouseBinExcelPo,warehouseBinExcelPo1);
                    warehouseBinExcelPo1.setFnskuName(x.getFnskuName());
                    warehouseBinExcelPo1.setProductName(x.getProductName());
                    warehouseBinExcelPo1.setShopName(x.getShopName());
                    warehouseBinExcelPo1.setSku(x.getSku());
                    QueryWrapper<InventoryPlacement> queryWrapper=new QueryWrapper();
                    queryWrapper.eq("stock_id",warehouseBinItemDVo.getWarehouseId());
                    queryWrapper.eq("item_id",x.getProductId());
                    queryWrapper.eq("bin_id",warehouseBinItemDVo.getId());

                    if(x.getShopId()!=null){
                        queryWrapper.eq("shop_id",x.getShopId());
                        try {
                            warehouseBinExcelPo1.setShopName(shopInfoService.getVoById(x.getShopId()).getShopName());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }else{
                        queryWrapper.isNull("shop_id");
                    }
                    if(x.getFnsku()!=null){
                        queryWrapper.eq("fn_sku",x.getFnskuName());
                    }else{
                        queryWrapper.isNull("fn_sku");
                    }
                    InventoryPlacement one = inventoryPlacementService.getOne(queryWrapper);
                    warehouseBinExcelPo1.setQuantity(one!=null?one.getStockQty().toString():"0");
                    items.add(warehouseBinExcelPo1);
                });
            }
        }
        String fileName = String.format("仓位产品关系(%s).xlsx", DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME));
        ResponseUtils.setAttachmentFileName(response, fileName);
        EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(new CustomExcelHandler())
                .sheet()
                .head(warehouseBinProductExcelPo.class)
                .doWrite(items);
    }

    public List<WarehouseBinStockVo> getBinByWarehouse(WarehouseBinParam search) throws Exception {
        List<WarehouseBinStockVo> list = warehouseBinDMapper.selectBinByWarehouse(search);
        if(CollectionUtil.isEmpty(list)){
            Integer type = 0;
            if(search.getType().equals(5L)){
                type = 2;
            }else if(search.getType().equals(6L)){
                type = 3;
            }else{
                throw new Exception("仓位类型错误");
            }
            WarehouseBin warehouseBin = warehouseBinMapper.selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                    .eq(WarehouseBin::getWarehouseId,search.getWarehouseId())
                    .eq(WarehouseBin::getType,type));
            if(null == warehouseBin){
                return list;
            }
            WarehouseBinStockVo vo = new WarehouseBinStockVo();
            BeanUtil.copyProperties(warehouseBin,vo);

            QueryWrapper<InventoryPlacement> queryWrapper=new QueryWrapper();
            Product product =  productService.getOne(Wrappers.lambdaQuery(Product.class).eq(Product::getSku,search.getSku()));

            queryWrapper.eq("stock_id",search.getWarehouseId());
            queryWrapper.eq("item_id",product.getId());
            queryWrapper.eq("bin_id",warehouseBin.getId());

            if(search.getShopId()!=null){
                queryWrapper.eq("shop_id",search.getShopId());
            }else{
                queryWrapper.isNull("shop_id");
            }
            if(StringUtils.hasText(search.getFnskuName())){
                queryWrapper.eq("fn_sku",search.getFnskuName());
            }else{
                queryWrapper.isNull("fn_sku");
            }
            InventoryPlacement one = inventoryPlacementService.getOne(queryWrapper);
            vo.setStockQty(one!=null?one.getStockQty().intValue():0);

            list.add(vo);
        }
        return list;
    }

    public Page<WarehouseBinStockVo> getBinPageByWarehouse(WarehouseBinParam search) throws Exception{
        return warehouseBinDMapper.selectBinByWarehousePage(search.toPage(),search);
    }

    /**
     * 入库仓位
     * @param search
     * @return
     */
    public Page<WarehouseBin> getStockInBinPage(WarehouseBinParam search) throws Exception {
        Page<WarehouseBin> result = warehouseBinDMapper.selectStockInBinPage(search.toPage(),search);
        List<WarehouseBin> list = result.getRecords();
        if(CollectionUtil.isEmpty(list)){
            Integer type = 0;
            if(search.getType().equals(5L)){
                type = 2;
            }else if(search.getType().equals(6L)){
                type = 3;
            }else{
                throw new Exception("仓位类型错误");
            }
            WarehouseBin warehouseBin = warehouseBinMapper.selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                    .eq(WarehouseBin::getWarehouseId,search.getWarehouseId())
                    .eq(WarehouseBin::getType,type));

            list = new ArrayList<>();
            list.add(warehouseBin);
            result.setRecords(list);
            result.setTotal(list.size());
        }
        return result;
    }

    public List<OptionItem<WarehouseBinItemVo>> searchOptions(WarehouseBinParam search) throws Exception {
        List<OptionItem<WarehouseBinItemVo>> optionItems = this.warehouseBinDMapper.searchOptions(search);
        if(CollectionUtil.isEmpty(optionItems)){
            Integer type = 0;
            if(search.getType().equals(5L)){
                type = 2;
            }else if(search.getType().equals(6L)){
                type = 3;
            }else{
                throw new Exception("仓位类型错误");
            }
            WarehouseBin warehouseBin = warehouseBinMapper.selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                    .eq(WarehouseBin::getWarehouseId,search.getWarehouseId())
                    .eq(WarehouseBin::getType,type));
            WarehouseBinItemVo vo = new WarehouseBinItemVo();
            BeanUtils.copyProperties(warehouseBin,vo);
            OptionItem<WarehouseBinItemVo> optionItem = new OptionItem();
            optionItem.setValue(vo.getId().toString());
            optionItem.setLabel(vo.getStorageBin());
            optionItem.setData(vo);
            optionItems.add(optionItem);
        }
        return optionItems;
    }

    public List<ImportRow<WarehouseBinTransferImportPo>> importPreview3(SysFile sysFile,
                                                                        Long templateId, boolean allowOverrides, Long wid) throws IOException {

        SysImportTemplate importTemplate = null;
        if (templateId != null && templateId > 0) {
            importTemplate = importTemplateService.getById(templateId);
            if (importTemplate == null) {
                throw new RException("指定的模版不可用！");
            }
        }
        Map<String, Object> variables = new HashMap<>();
        try (InputStream in = fileService.read(sysFile)) {
            List<ImportRow<WarehouseBinTransferImportPo>> rows = new ArrayList<>();

            // 读取 Excel 到 rows
            EasyExcel
                    .read(in)
                    .useDefaultListener(false)
                    .registerReadListener(
                            new TemplateModelBuildEventListener<>(
                                    WarehouseBinTransferImportPo.class,
                                    importTemplate
                            ) {
                                @Override
                                public void invokeRow(
                                        WarehouseBinTransferImportPo row,
                                        AnalysisContext cxt
                                ) {
                                    WarehouseBinVo vo = new WarehouseBinVo();
                                    ImportRow<WarehouseBinTransferImportPo> ir = excelToImportRow4(
                                            row,
                                            cxt.readRowHolder().getRowIndex(),
                                            vo,
                                            variables,
                                            allowOverrides
                                    );
                                    if (ir.isEmptyRow()) {
                                        return;
                                    }
                                    if (allowOverrides) {
                                        // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
                                    }
                                    rows.add(ir);
                                }
                            }
                    )
                    .sheet()
                    .doRead();
            return rows;
        }

    }

    private ImportRow<WarehouseBinTransferImportPo> excelToImportRow4(WarehouseBinTransferImportPo row, Integer rowNumber,
                                                                      WarehouseBinVo vo, Map<String, Object> variables,
                                                                      boolean allowOverrides) {
        ImportRow<WarehouseBinTransferImportPo> ir = new ImportRow<WarehouseBinTransferImportPo>();
        ir.setRowNumber(rowNumber);
        ir.setRow(row);
        if (SheetUtils.isAllFieldsEmpty(row)) {
            ir.setEmptyRow(true);
            ir.addError("", "空行");
            return ir;
        }
        final Set<ConstraintViolation<WarehouseBinTransferImportPo>> validate = validator.validate(
                row
        );
        boolean isOutputVo = vo != null;
        if (!isOutputVo) {
            vo = new WarehouseBinVo();
        }
        BeanUtils.copyProperties(row, vo);
        // 收集基本校验错误
        ir.initErrors(validate, WarehouseBinTransferImportPo.class);
        // 一般数据处理
        ShopInfo shop=null;
        if (StringUtils.hasText(row.getShop())) {
             shop =  shopInfoService.getOne(Wrappers.<ShopInfo>query().lambda().eq(ShopInfo::getShopName, row.getShop()));
            if (shop == null) {
                ir.addError("shop", "店铺不存在");
            }else{
                row.setShopName(shop.getShopName());
                row.setShopId(shop.getId());
            }
        }
        Product product=null;
        if (StringUtils.hasText(row.getSku())) {
             product = productService.getOne(Wrappers.<Product>query().lambda().eq(Product::getSku, row.getSku()));
            if (product == null) {
                ir.addError("sku", "产品不存在");
            }else{
                row.setProductName(product.getName());
                row.setProductId(product.getId());
            }
        }
        Warehouse warehouse=null;
        if (StringUtils.hasText(row.getWidName())) {
             warehouse = warehouseService.getOne(Wrappers.<Warehouse>query().lambda().eq(Warehouse::getName, row.getWidName()));
            if (warehouse == null) {
                ir.addError("widName", "仓库不存在");
            }else{
                row.setWid(warehouse.getId());
                row.setWidName(warehouse.getName());
            }
        }
        WarehouseBin warehouseBin=null;
        if (StringUtils.hasText(row.getOrgBin())) {
             warehouseBin = warehouseBinMapper.selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                             .eq(WarehouseBin::getWarehouseId,warehouse.getId())
                    .eq(WarehouseBin::getStorageBin,row.getOrgBin()));
            String newBin = row.getNewBin();
            try {
                BigDecimal bigDecimal = new BigDecimal(newBin);
                BigDecimal bigDecimal1 = bigDecimal.setScale(0);
                newBin=bigDecimal1.toString();
            }catch (Exception e) {

            }
            WarehouseBin   warehouseBin2 = warehouseBinMapper.selectOne(Wrappers.lambdaQuery(WarehouseBin.class)
                    .eq(WarehouseBin::getWarehouseId,warehouse.getId())
                    .eq(WarehouseBin::getStorageBin,newBin));
                    if(warehouseBin2!=null){
                        row.setToBinId(warehouseBin2.getId());
                    }
            if (warehouseBin == null) {
                ir.addError("orgBin", "原仓位不存在");
            }else{
                row.setBinType(warehouseBin.getType());
                row.setType_name("可用");
                row.setStorageId(warehouseBin.getId());
            }
//            if(warehouseBin!=null){
//                Warehouse byId = warehouseService.getById(warehouseBin.getWarehouseId());
//                row.setWid(byId.getId());
//                row.setWidName(byId.getName());
//            }
        }
        row.setDefectQty(row.getQuantity());
        if(product!=null&&warehouseBin!=null&&shop!=null){
            QueryWrapper<InventoryPlacement> queryWrapper=new QueryWrapper();
            queryWrapper.eq("stock_id",warehouseBin.getWarehouseId());
            queryWrapper.eq("item_id",product.getId());
            queryWrapper.eq("bin_id",warehouseBin.getId());

            if(StringUtils.hasText(row.getOrgBin())){
                queryWrapper.eq("shop_id",shop.getId());
            }else{
                queryWrapper.isNull("shop_id");
            }
            if(StringUtils.hasText(row.getFnsku())){
                queryWrapper.eq("fn_sku",row.getFnsku());
            }else{
                queryWrapper.isNull("fn_sku");
            }
            InventoryPlacement one = inventoryPlacementService.getOne(queryWrapper);
            if (one == null) {
                ir.addError("可转移量", "仓位数据不存在");
            }else{
                row.setStock_qty(one.getStockQty().toString());
            }
        }
        return ir;
    }
}
